package com.crm.services;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.model.jdao.ICompetitorDAO;
import com.crm.model.jdao.ISalesTrackingLogDAO;
import com.crm.model.pojo.Competitor;
import com.crm.model.pojo.Contact;
import com.crm.model.pojo.Customer;
import com.crm.model.pojo.SalesOpportunity;

/**
 * 竞争对手services
 * @author 飞鱼
 *
 */
@Service
public class CompetitorServices  {

	@Autowired
	private ICompetitorDAO CompetitorDAO;
	//@Autowired
	//private ICompetitorDAO salDAO;
	@Autowired
	private CompetitorServices coms;
	@Autowired
	private DictionaryServices ds;
	@Autowired
	private UserServices us;	
	//@Autowired
	//private IShowsettingCompetitorDAO sssDAO;	
	//@Autowired
	private ISalesTrackingLogDAO salLogDAO;
	private static int count=0;

	/**
	 * 销售机会新增
	 * @param sale
	 * @return
	 */
	public int save(Competitor newsale) {
		if(newsale.getSalesOpportunity().getSalStage()<1328) {
			newsale.getSalesOpportunity().setSalStage(1328);
		}
		CompetitorDAO.save(newsale);		
		return 1;		
	}
	/**
	 * 
	 * @param pageNumber  从那天开始显示
	 * @param pageContent 显示的记录条数
	 * @return
	 */
	public List<Competitor> queryByAll(int pageNumber,int pageContent,String[] DId){
		System.out.println("11112333");
		Sort sort=Sort.by(Direction.DESC, "comId");
		Pageable pageable =PageRequest.of(pageNumber,pageContent,sort);	
		//查询条件构造
		 Specification<Competitor> spec=new Specification<Competitor>(){

			@Override
			public Predicate toPredicate(Root<Competitor> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				//Path<Object> state=root.get("state");
				List<Predicate> list=new ArrayList<>();
				System.out.println("ss的DId:"+DId);
					if(DId.length==0) {
						list.add(cb.equal(root.get("state").as(Integer.class), 1));
					}
					int i=0;
					for (String str : DId) {
						System.out.println("str:"+str);
						if("全部数据".equals(str)) {
							 list.add(cb.equal(root.get("state").as(Integer.class), 1));	
						}
						if("竞争能力".equals(str)) {
							System.out.println("触发了竞争能力数据筛选");
							 list.add(cb.equal(root.get("comPower").as(Integer.class), DId[i+1]));							
						}
						if("客户名称".equals(str)) {
							System.out.println("触发了模糊客户名称数据筛选");	
							//cb.countDistinct(root.join("customer").get("custName")));
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.join("customer").get("custName").as(String.class),"%"+DId[i+2]+"%"));									
							}else {
								list.add(cb.like(root.join("customer").get("custName").as(String.class),"%"+DId[i+1]+"%"));
							    query.groupBy(root.get("customer").as(Customer.class));
							}

						}
						if("公司名".equals(str)) {
							System.out.println("触发了模糊公司名数据筛选");	
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.get("comName").as(String.class),"%"+DId[i+2]+"%"));								
							}else {
								list.add(cb.like(root.get("comName").as(String.class),"%"+DId[i+1]+"%"));
								query.groupBy(root.get("comName").as(String.class));
								System.out.println("分组");
							}

							//cb.countDistinct(root.join("customer").get("custName")));
							
						}
						if("机会主题".equals(str)) {
							System.out.println("触发了模糊机会主题数据筛选");	
							if("不分组".equals(DId[i+1])) {
								list.add(cb.like(root.join("salesOpportunity").get("salTheme").as(String.class),"%"+DId[i+2]+"%"));									
							}else {
								list.add(cb.like(root.join("salesOpportunity").get("salTheme").as(String.class),"%"+DId[i+1]+"%"));	
								 query.groupBy(root.get("salesOpportunity").as(SalesOpportunity.class));
							}							
													
						}
						i++;
					}

		        Predicate[] p = new Predicate[list.size()];
		        System.out.println("-----------------------------------------");
			    query.where(list.toArray(p));
				return query.getRestriction();
			}
			 
		 };
		Page<Competitor> page =CompetitorDAO.findAll(spec,pageable);		
		System.out.println("总记录数："+page.getTotalElements());
		count=(int) page.getTotalElements();
		List<Competitor> list=page.getContent();
		return list;	
		//return null;
	}
	
	/**
	 *将list的数据转换成JsonArray的数据
	 * @return
	 */
	public JSONArray ListTransJSONArray(int pageNumber,int pageContent,String[] DId) {
		JSONArray array =new JSONArray();
		List<Competitor> list=coms.queryByAll(pageNumber,pageContent,DId);
		for (Competitor Competitor : list) {
		//System.out.println("Competitor:"+Competitor);
			JSONObject obj = new JSONObject();		
			array.add(toJSONObject1( obj,Competitor));
	}
		return array;
	}
	
	/**
	 * 销售机会转JSONObject
	 * @param obj
	 * @param Competitor
	 * @return
	 */
	public JSONObject toJSONObject1(JSONObject obj,Competitor Competitor) {
		/*obj.put("salId", Competitor.getSalId());
		obj.put("salTheme", Competitor.getSalTheme());
		obj.put("custName", Competitor.getCustomer().getCustName());
		String starURL=ss.starURL(Competitor.getStarStandard());
		obj.put("starStandard",starURL);
		obj.put("salType", ds.findByDictId(Competitor.getSalType()));
		if(Competitor.getSotlDate()!=null) {
			obj.put("sotlDate",Competitor.getSotlDate().toString());			
		}				
		obj.put("sotlMoney", Competitor.getSotlMoney());
		obj.put("custDemand", Competitor.getCustDemand());
		obj.put("salStageStop", Competitor.getSalStageStop()+"天");
		obj.put("salState",Competitor.getSalState());
		obj.put("salSource", ds.findByDictId(Competitor.getSalSource()));
		obj.put("sotlId", ss.findByUserName(Competitor.getSotlId()));
		obj.put("salState", ds.findByDictId(Competitor.getSalState())+"");		
		obj.put("salPossibility", ds.findByDictId(Competitor.getSalPossibility()));
		obj.put("salUpdatetime", Competitor.getSalUpdatetime().toString());
		//obj.put("", value);*/
		obj.put("comId", Competitor.getComId());
		obj.put("advantages", Competitor.getAdvantages());
		obj.put("comName", Competitor.getComName());
		obj.put("comPower", ds.findByDictId(Competitor.getComPower()));	
		obj.put("comPrice", price(Competitor.getComPrice()));
		obj.put("comStrategies", Competitor.getComStrategies());
		obj.put("inferiority", Competitor.getInferiority());
		obj.put("salesOpportunity",Competitor.getSalesOpportunity().getSalTheme());
		obj.put("customer", Competitor.getCustomer().getCustName());
		return obj;
	}
	/**
	 * 处理价格的显示:￥38,000.00
	 * @param price
	 * @return
	 */
	public String Price(Double price) {
		//拆包
		double priceDouble=Double.valueOf(price);
		int priceInt=(int)priceDouble;
		System.out.println();
		StringBuilder sb=new StringBuilder('￥');
		if(price>=10000) {
			sb.append(",");
		}
		
		return null;
		
	}
	
	/**
	 * 将list的数据转换成JsonArray的数据,用于页面搜索查询客户信息
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray1(List<Competitor> list) {
		JSONArray array = new JSONArray();
		for (Competitor Competitor : list) {
			// System.out.println("Competitor:"+Competitor);
			JSONObject obj = new JSONObject();
			
			obj.put("value", Competitor.getCustomer().getCustName());
			obj.put("label1", Competitor.getCustomer().getCustId());
			array.add(obj);
		}
		return array;
	}	
	
	/** 销售机会转JSONObject,单一saleOpp
	 * @param obj
	 * @param Competitor
	 * @return
	 */
	public JSONObject toJSONObject2(JSONObject obj,Competitor Competitor) {
		/*
		obj.put("salId", Competitor.getSalId());
		obj.put("salTheme", Competitor.getSalTheme());
		obj.put("customerName", Competitor.getCustomer().getCustName());
		obj.put("customerId", Competitor.getCustomer().getCustId()+"");			
		obj.put("starStandard",Competitor.getStarStandard()+"");
		
		obj.put("salTypelabel", ds.findByDictId(Competitor.getSalType()));
		obj.put("salTypeValue", Competitor.getSalType());
		
		//obj.put("sotlId", Competitor.getSotlId());	
		if(Competitor.getSotlDate()!=null) {
			obj.put("sotlDate",Competitor.getSotlDate().toString());			
		}		
		obj.put("sotlMoney", Competitor.getSotlMoney());
		//
		obj.put("custDemand", Competitor.getCustDemand());
		
		obj.put("salStageStop", Competitor.getSalStageStop()+"天");		
		obj.put("salState", Competitor.getSalState()+"");		
		obj.put("salPossibilitylabel", ds.findByDictId(Competitor.getSalPossibility()));

		obj.put("sotlId", ss.findByUserName(Competitor.getSotlId()));
		obj.put("salStagelabel", ds.findByDictId(Competitor.getSalStage()));
		obj.put("salStageNotes", Competitor.getSalStageNotes());
		
		obj.put("salSourcelabel", ds.findByDictId(Competitor.getSalSource()));
		if(Competitor.getContact()!=null) {
			obj.put("contactName", Competitor.getContact().getConName()+"");			
		}else {
			obj.put("contactName","");				
		}
		obj.put("contactId", Competitor.getContact().getConId());
		*/
		obj.put("comId", Competitor.getComId());
		obj.put("advantages", Competitor.getAdvantages());
		obj.put("comName", Competitor.getComName());
		obj.put("comPower", ds.findByDictId(Competitor.getComPower()));	
		obj.put("comPrice", Competitor.getComPrice());
		obj.put("comStrategies", Competitor.getComStrategies());
		obj.put("inferiority", Competitor.getInferiority());
		obj.put("competingProduct", Competitor.getCompetingProduct());
		obj.put("salesOpportunityName",Competitor.getSalesOpportunity().getSalTheme());
		obj.put("salesOpportunityId", Competitor.getSalesOpportunity().getSalId());
		//obj.put("customer", Competitor.getCustomer().getCustName());
		obj.put("customerName", Competitor.getCustomer().getCustName());
		obj.put("customerId", Competitor.getCustomer().getCustId()+"");	
		return obj;
	}
	
	/**
	 * 价格的显示：￥38,000.00
	 */
	public String price(BigDecimal bigDecimal) {
		if(bigDecimal==null) {
			return "￥0.00";
		}		
		//拆包
		double priceDouble=bigDecimal.doubleValue();
		int priceInt=(int)priceDouble;
		//获取后面的小数
		int decimal=(int) ((priceDouble-priceInt)*100);
		StringBuilder sb=new StringBuilder("￥");
		ArrayList<Integer> list=new ArrayList();
		decompositionOfNumbers(priceInt,list);
		System.out.println(list);
		list.get(list.size()-1);
		for(int i=list.size()-1;i>=0;i--) {
			if(i!=0&&i%3==0) {
				sb.append(list.get(i)+",");
			}else {
				sb.append(list.get(i));
			}
			
		}
		if(decimal==0) {
			sb.append(".00");
		}else {
			sb.append("."+decimal);			
		}
		return sb.toString();
		
	}
	/**
	 * 价格的显示：￥38,000.00
	 */
	public String price(Double price) {
		if(price==null) {
			return "￥0.00";
		}
		//拆包
		double priceDouble=Double.valueOf(price);
		int priceInt=(int)priceDouble;
		//获取后面的小数
		int decimal=(int) ((priceDouble-priceInt)*100);
		StringBuilder sb=new StringBuilder("￥");
		ArrayList<Integer> list=new ArrayList();
		list=decompositionOfNumbers(priceInt,list);
		System.out.println("list:"+list);
		for(int i=list.size()-1;i>=0;i--) {
			if(i!=0&&i%3==0) {
				sb.append(list.get(i)+",");
			}else {
				sb.append(list.get(i));
			}
			
		}
		//System.out.println("decimal:"+decimal);
		if(decimal==0) {
			sb.append(".00");
		}else {
			sb.append("."+decimal);			
		}

		return sb.toString();
		
	}	
	/**
	 * 分解整数
	 * @param price
	 * @param list
	 * @return
	 */
	private ArrayList<Integer> decompositionOfNumbers(int price,ArrayList<Integer> list) {
		//除法和取余法
		int a=price/10;
		int b=price%10;
		if(a>=10) {	
			list.add(b);
			return decompositionOfNumbers(a,list);
		}else {
			if(a==0) {
				list.add(b);
				return list;
			}
			list.add(b);
			list.add(a);
			return list;
		}
		
	}
	
	/**
	 * 将list的数据转换成JsonArray的数据,用于页面搜索查询销售机会主题名称信息
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray3(List<Competitor> list) {
		JSONArray array = new JSONArray();
		for (Competitor salesOpportunity : list) {
			// System.out.println("salesOpportunity:"+salesOpportunity);
			JSONObject obj = new JSONObject();
			obj.put("value", salesOpportunity.getSalesOpportunity().getSalTheme());
			array.add(obj);
		}
		return array;
	}
	/**
	 * 将list的数据转换成JsonArray的数据,用于页面搜索查询公司名信息
	 * 
	 * @return
	 */
	public JSONArray ListTransJSONArray4(List<Competitor> list) {
		JSONArray array = new JSONArray();
		for (Competitor Competitor : list) {
			// System.out.println("Competitor:"+Competitor);
			JSONObject obj = new JSONObject();
			
			obj.put("value", Competitor.getComName());
			array.add(obj);
		}
		return array;
	}	
	/**
	 * 统计对象个数
	 * @return
	 */
	public int queryByCount() {
		return count;
		
	}
	  /**
	   * 根据id查询竞争对手
	   * @param salId
	   * @return
	   */
	public  JSONObject findBySalId(Integer salId) {
		Competitor sale=CompetitorDAO.findByComId(salId);
		JSONObject obj = new JSONObject();	
		return toJSONObject2(obj,sale);
		  
	  }
	/**
	 * 删除单个销售机会
	 * @param salId
	 * @return
	 */
	public void Delete(Integer salId) {
		Competitor sal=CompetitorDAO.findById(salId).get();
		sal.setState(0);
		CompetitorDAO.save(sal);		
	}
	
	/**
	 * 批量逻辑删除
	 * @param salIds
	 */
	public void DeleteAll(Iterable<Integer> salIds) {
		//Integer[] ff=new Integer[] {1,2,3};
		/*List list=new ArrayList();
		list.add(1);
		Iterable<Integer> dd=(Iterable<Integer>) list.iterator();
		ss.DeleteAll(dd);*/		
		Iterable<Competitor> a=CompetitorDAO.findAllById(salIds);
		for (Competitor Competitor : a) {
			Competitor.setState(0);
		}
		CompetitorDAO.saveAll(a);
	}
	
	


}
